package com.oasen.learn.usercenter.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.PoolConfig;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import redis.clients.jedis.JedisPoolConfig;

@Configuration
@ComponentScan(basePackages={"com.oasen.learn.usercenter"},
		excludeFilters={
				@Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class),
				@Filter(type=FilterType.ANNOTATION,value=Controller.class)})
@ImportResource({"classpath:spring-base.xml"})
public class RootConfig {
	
	@Value("${redis.host}")
	private String host;
	@Value("${redis.port}")
	private String port;
	@Value("${redis.maxIdle}")
	private int maxIdle;
	@Value("${redis.maxActive}")
	private int maxActive;
	@Value("${redis.maxWait}")
	private int maxWait;
	@Value("${redis.testOnBorrow}")
	private boolean testOnBorrow;
	@Value("${redis.timeout}")
	private int timeout;
	
	@Bean
	public JedisPoolConfig jedisPoolConfig(){
		JedisPoolConfig pool = new JedisPoolConfig();
		pool.setMaxIdle(maxIdle);
		pool.setMaxWaitMillis(maxWait);
		pool.setTestOnBorrow(testOnBorrow);
		return pool;
	}
	
	@Bean
	public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig){
		JedisConnectionFactory jedisFactory = new JedisConnectionFactory();
		jedisFactory.setHostName(host);
		jedisFactory.setPort(6379);
		jedisFactory.setTimeout(timeout);
		jedisFactory.setPoolConfig(jedisPoolConfig);
		return jedisFactory;
	}
	
	@Bean
	public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf){
		RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(cf);
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.setValueSerializer(new StringRedisSerializer());
		return redisTemplate;
	}
}
